package com.runa.monitor.platinterface.dispatch.conn;

import com.alibaba.fastjson.JSON;
import com.google.protobuf.ProtocolStringList;
import com.runa.monitor.comm.constants.ResultConstants;
import com.runa.persistence.util.SpringContextUtil;
import com.runa.monitor.platinterface.dispatch.conn.gen.*;
import com.runa.monitor.platinterface.dispatch.grpcComm.*;
import com.runa.monitor.platinterface.dispatch.grpcComm.BuildValveControlOfOpenVO;
import com.runa.monitor.platinterface.extend.data.service.DataProcessService;
import com.runa.monitor.platinterface.platService.pojo.GatewayDeviceParameter;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import org.lognet.springboot.grpc.GRpcService;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.Executor;

@Slf4j
@GRpcService
public class Server extends COMMDispatchGrpc.COMMDispatchImplBase {

    @Resource(name = "asyncRequestScheduler")
    private Executor executor;

    @Resource
    private DataProcessService dataProcessService;

    @Override
    public void readFmuNow(ReadFmuNowVO request, StreamObserver<ResultComm> responseObserver) {
        log.info("业务请求—立即抄表 网络设备号：{}, 任务号：{}, holdInfo: {}", request.getFmuSerial(), request.getTaskNo(), request.getHoldInfo());
        executor.execute(() -> {
//            interfaceService.readFmuNow(request.getFmuSerial(), request.getTaskNo(), request.getHoldInfo());
        });
        responseObserver.onNext(ResultComm.newBuilder().setCode(ResultConstants.CODE_200).setMsg("下发成功").build());
        responseObserver.onCompleted();
    }

    @Override
    public void sentEquArchive(SentEquArchiveVO request, StreamObserver<ResultComm> responseObserver) {
        log.info("业务请求—网络设备下发档案开始  网络设备号：{}, 档案信息：{}, 任务号：{}, holdInfo: {}", request.getFmuSerial(), request.getRunaEquArchive(), request.getTaskNo(), request.getHoldInfo());
        executor.execute(() -> {
//            interfaceService.rccSentEquArchive(request.getFmuSerial(), request.getTaskNo(), JSON.parseArray(request.getRunaEquArchive(), RunaEquArchive.class), request.getHoldInfo());
        });
        responseObserver.onNext(ResultComm.newBuilder().setCode(ResultConstants.CODE_200).setMsg("下发成功").build());
        responseObserver.onCompleted();
    }

    @Override
    public void clearEquArchive(ClearEquArchiveVO request, StreamObserver<ResultComm> responseObserver) {
        log.info("业务请求—清除档案  网络设备号：{}, 任务号：{}, holdInfo: {}", request.getFmuSerial(), request.getTaskNo(), request.getHoldInfo());
        executor.execute(() -> {
//            interfaceService.rccClearEquArchive(request.getFmuSerial(), request.getTaskNo(), request.getHoldInfo());
        });
        responseObserver.onNext(ResultComm.newBuilder().setCode(ResultConstants.CODE_200).setMsg("下发成功").build());
        responseObserver.onCompleted();
    }

    @Override
    public void readEquArchive(ReadEquArchiveVO request, StreamObserver<ResultComm> responseObserver) {
        log.info("业务请求—网络设备读档案 request:{}", JSON.toJSONString(request.getAllFields()));
        executor.execute(() -> {
//            interfaceService.readEquArchive(request.getFmuSerial(), request.getTaskNo(), request.getIndexesList(), request.getHoldInfo());
        });
        responseObserver.onNext(ResultComm.newBuilder().setCode(ResultConstants.CODE_200).setMsg("下发成功").build());
        responseObserver.onCompleted();
    }


    @Override
    public void setMeterReadingCycleParameter(SetMeterReadingCycleParameterVO request, StreamObserver<ResultComm> responseObserver) {
        log.info("业务请求—网络设备周期设定 request:{}", JSON.toJSONString(request.getAllFields()));
        executor.execute(() -> {
            SetMeterReadingCycleParameterPOJO setMeterReadingCycleParameterPOJO = JSON.parseObject(request.getJson(), SetMeterReadingCycleParameterPOJO.class);
            GatewayDeviceParameter gatewayDeviceParameter = new GatewayDeviceParameter();
            gatewayDeviceParameter.setMinuteOfCollectForHouse(setMeterReadingCycleParameterPOJO.getMinuteOfCollect());
            gatewayDeviceParameter.setMinuteOfCollectForBuild(setMeterReadingCycleParameterPOJO.getMinuteOfCollect());
            gatewayDeviceParameter.setMinuteOfUploadForBuild(setMeterReadingCycleParameterPOJO.getMinuteOfUpload());
            gatewayDeviceParameter.setMinuteOfUploadForHouse(setMeterReadingCycleParameterPOJO.getMinuteOfUpload());
//            interfaceService.setMeterReadingCycleParameter(request.getFmuSerial()
//                    , setMeterReadingCycleParameterPOJO.getTask()
//                    , gatewayDeviceParameter
//                    , setMeterReadingCycleParameterPOJO.getHoldInfo());
        });
        responseObserver.onNext(ResultComm.newBuilder().setCode(ResultConstants.CODE_200).setMsg("下发成功").build());
        responseObserver.onCompleted();
    }

    @Override
    public void readMeterReadingCycleParameter(ReadMeterReadingCycleParameterVO request, StreamObserver<ResultComm> responseObserver) {
        log.info("业务请求—网络设备读周期 request:{}", JSON.toJSONString(request.getAllFields()));
        executor.execute(() -> {
//            interfaceService.readMeterReadingCycleParameter(request.getFmuSerial(), request.getTaskNo(), request.getHoldInfo());
        });
        responseObserver.onNext(ResultComm.newBuilder().setCode(ResultConstants.CODE_200).setMsg("下发成功").build());
        responseObserver.onCompleted();
    }

    @Override
    public void setFlowLimit(SetFlowLimitVO request, StreamObserver<ResultComm> responseObserver) {
        log.info("业务请求—网络设备流量超限设定 request:{}", JSON.toJSONString(request.getAllFields()));
        executor.execute(() -> {
//            interfaceService.flowLimitSetting(request.getFmuSerial(), request.getTaskNo(), request.getValue()
//                    , request.getPriority(), request.getHoldInfo());
        });
        responseObserver.onNext(ResultComm.newBuilder().setCode(ResultConstants.CODE_200).setMsg("下发成功").build());
        responseObserver.onCompleted();
    }

    @Override
    public void readMeter(ReadMeterVO request, StreamObserver<ResultComm> responseObserver) {
        log.info("业务请求—网络设备读表 request:{}", JSON.toJSONString(request.getAllFields()));
//        executor.execute(() -> {
//        interfaceService.rccReadNodeData(request.getTaskNo(), request.getHoldInfo(), request.getMetersList(), EquData.EquDataType.METER);
//        });
        responseObserver.onNext(ResultComm.newBuilder().setCode(ResultConstants.CODE_200).setMsg("下发成功").build());
        responseObserver.onCompleted();
    }

    @Override
    public void readElecMeter(ReadElecMeterVO request, StreamObserver<ResultComm> responseObserver) {
        log.info("业务请求—网络设备读电表 request:{}", JSON.toJSONString(request.getAllFields()));
        executor.execute(() -> {
//            interfaceService.rccReadNodeDataOfElec(request.getMeters(0), request.getTaskNo(), request.getHoldInfo());
        });
        responseObserver.onNext(ResultComm.newBuilder().setCode(ResultConstants.CODE_200).setMsg("下发成功").build());
        responseObserver.onCompleted();
    }

    @Override
    public void readValve(ReadValveVO request, StreamObserver<ResultComm> responseObserver) {
        log.info("业务请求—网络设备读阀 request:{}", JSON.toJSONString(request.getAllFields()));
        executor.execute(() -> {
//            interfaceService.rccReadNodeData(request.getTaskNo(), request.getHoldInfo(), request.getValvesList(), EquData.EquDataType.VALVE);
        });
        responseObserver.onNext(ResultComm.newBuilder().setCode(ResultConstants.CODE_200).setMsg("下发成功").build());
        responseObserver.onCompleted();
    }

    @Override
    public void readPanel(ReadPanelVO request, StreamObserver<ResultComm> responseObserver) {
        log.info("业务请求—网络设备读面板 request:{}", JSON.toJSONString(request.getAllFields()));
        executor.execute(() -> {
//            interfaceService.rccReadNodeData(request.getTaskNo(), request.getHoldInfo(), request.getPanelsList(), EquData.EquDataType.TEMPERATURE_PANEL);
        });
        responseObserver.onNext(ResultComm.newBuilder().setCode(ResultConstants.CODE_200).setMsg("下发成功").build());
        responseObserver.onCompleted();
    }

    @Override
    public void buildValveParam(BuildValveParamVO request, StreamObserver<ResultComm> responseObserver) {
        log.info("业务请求—读楼站阀门参数 request:{}", JSON.toJSONString(request.getAllFields()));
        executor.execute(() -> {
            ProtocolStringList valvesList = request.getValvesList();
            int mo = 0;
            if (request.getModel().equalsIgnoreCase("PID")) {
                mo = 3;
            } else if (request.getModel().equalsIgnoreCase("单元调控策略")) {
                mo = 1;
            } else if (request.getModel().equalsIgnoreCase("开度限值")) {
                mo = 4;
            }
//            for (String s : valvesList) {
//                int finalMo = mo;
//            interfaceService.buildValveParam(request.getTaskNo(), valvesList, mo, request.getHoldInfo());
//            }
        });
        responseObserver.onNext(ResultComm.newBuilder().setCode(ResultConstants.CODE_200).setMsg("下发成功").build());
        responseObserver.onCompleted();
    }

    @Override
    public void buildValveControl(BuildValveControlVO request, StreamObserver<ResultComm> responseObserver) {
//        log.info("业务请求—楼站(户)阀门控制 request:{}", JSON.toJSONString(request.getAllFields()));
//        log.info("业务请求—楼站(户)阀门控制 taskNo:{}======holdInfo:{}======getValveControlList:{}", request.getTaskNo(), request.getHoldInfo(), request.getValveControlList().toString());
        log.info("业务请求—楼站(户)阀门控制 taskNo:{}======holdInfo:{}======getValveControlList:{}", request.getTaskNo(), request.getHoldInfo(), JSON.toJSONString(request.getValveControlList()));
        executor.execute(() -> {
//            interfaceService.buildValveControl(request.getTaskNo(), request.getHoldInfo(), request.getValveControlList());
        });
        responseObserver.onNext(ResultComm.newBuilder().setCode(ResultConstants.CODE_200).setMsg("下发成功").build());
        responseObserver.onCompleted();
    }

    //AI控制器无开度上下限接口
    @Override
    public void buildValveControlOfOpen(BuildValveControlOfOpenVO request, StreamObserver<ResultComm> responseObserver) {
        log.info("业务请求—网络设备下阀门开度上下限控制 request:{}", JSON.toJSONString(request.getAllFields()));
//        interfaceService.buildValveControlOfOpen(request.getTaskNo(), request.getHoldInfo(), request.getValveOpenLimitList());
        responseObserver.onNext(ResultComm.newBuilder().setCode(ResultConstants.CODE_200).setMsg("下发成功").build());
        responseObserver.onCompleted();
    }

    //这里只有集中器的，AI控制器单独接口
    @Override
    public void valveTemperatureControl(ValveTemperatureControlVO request, StreamObserver<ResultComm> responseObserver) {
        log.info("业务请求—温度上下限控制 request:{}", JSON.toJSONString(request.getAllFields()));
        executor.execute(() -> {
            List<ValveTemperatureLimit> valveTemperatureLimits = JSON.parseArray(request.getValveTemperature(), ValveTemperatureLimit.class);
//            for (ValveTemperatureLimit valveTemperatureLimit : valveTemperatureLimits) {
//            interfaceService.valveTemperatureControl(null, request.getTaskNo()
//                    , Collections.singletonList(valveTemperatureLimit.getValve()), null, null
//                    , valveTemperatureLimit.getUp()
//                    , valveTemperatureLimit.getDown(), request.getHoldInfo());
//            }
//            interfaceService.valveTemperatureControlT(request.getTaskNo(), request.getHoldInfo(), valveTemperatureLimits);
        });
        responseObserver.onNext(ResultComm.newBuilder().setCode(ResultConstants.CODE_200).setMsg("下发成功").build());
        responseObserver.onCompleted();
    }

    @Override
    public void valveTemperatureComp(ValveTemperatureCompVO request, StreamObserver<ResultComm> responseObserver) {
        log.info("业务请求—户阀温度补偿 request:{}", JSON.toJSONString(request.getAllFields()));

        List<ValveTemperatureComp> valveTemperatureComps = JSON.parseArray(request.getValveTemperatureComp(), ValveTemperatureComp.class);
        for (ValveTemperatureComp valveTemperatureComp : valveTemperatureComps) {
            executor.execute(() -> {
//                interfaceService.valveTemperatureComp(request.getTaskNo(), request.getHoldInfo(), valveTemperatureComp.getValve(), valveTemperatureComp.getCompensation());
            });
        }

        responseObserver.onNext(ResultComm.newBuilder().setCode(ResultConstants.CODE_200).setMsg("下发成功").build());
        responseObserver.onCompleted();
    }

    @Override
    public void buildValveModel(BuildValveModelVO request, StreamObserver<ResultComm> responseObserver) {
        log.info("业务请求—楼站阀门模式本地/远程修改 request:{}", JSON.toJSONString(request.getAllFields()));

        List<ValveModel> valveModels = JSON.parseArray(request.getBuildValveModel(), ValveModel.class);
        for (ValveModel valveModel : valveModels) {
            executor.execute(() -> {
//                interfaceService.buildValveModel(request.getTaskNo(), request.getHoldInfo(), valveModel.getValve(), valveModel.getModel() == ValveModel.ModelEnum.远程);
            });
        }

        responseObserver.onNext(ResultComm.newBuilder().setCode(ResultConstants.CODE_200).setMsg("下发成功").build());
        responseObserver.onCompleted();
    }

    @Override
    public void buildValveModelOfTimeScheme(BuildValveModelOfTimeSchemeVO request, StreamObserver<ResultComm> responseObserver) {
        super.buildValveModelOfTimeScheme(request, responseObserver);
    }

    @Override
    public void buildValveModelOfPID(BuildValveModelOfPIDVO request, StreamObserver<ResultComm> responseObserver) {
        log.info("业务请求—设置PID request:{}", JSON.toJSONString(request.getAllFields()));
        executor.execute(() -> {
            List<ValvePID> valvePIDS = JSON.parseArray(request.getBuildValveModelOfPID(), ValvePID.class);
            for (ValvePID valvePID : valvePIDS) {
//                interfaceService.buildValveModelOfPID(request.getTaskNo(), request.getHoldInfo(), valvePID);
            }
        });
        responseObserver.onNext(ResultComm.newBuilder().setCode(ResultConstants.CODE_200).setMsg("下发成功").build());
        responseObserver.onCompleted();
    }


    @Override
    public void aiDownloadFile(AiDownloadFileVO request, StreamObserver<ResultComm> responseObserver) {
        log.info("业务请求—档案下发 request:{}", JSON.toJSONString(request.getAllFields()));
        executor.execute(() -> {
            AiDownloadFile aiDownloadFile = JSON.parseObject(request.getJson(), AiDownloadFile.class);
//            interfaceService.meterDownloadFile(aiDownloadFile.getTask(), aiDownloadFile.getHoldInfo()
//                    , aiDownloadFile);
        });
        responseObserver.onNext(ResultComm.newBuilder().setCode(ResultConstants.CODE_200).setMsg("下发成功").build());
        responseObserver.onCompleted();
    }

    @Override
    public void valveTemperatureControlOfAiStorm(ValveTemperatureControlOfAiStormVO request, StreamObserver<ResultComm> responseObserver) {
        log.info("业务请求—AI控制器温度上下限修改 request:{}", JSON.toJSONString(request.getAllFields()));
        executor.execute(() -> {
            ValveTemperatureControlOfAiStorm valveTemperatureControlOfAiStorm = JSON.parseObject(request.getValveTemperature(), ValveTemperatureControlOfAiStorm.class);
//            interfaceService.valveTemperatureControlOfAiStorm(valveTemperatureControlOfAiStorm);
        });
        responseObserver.onNext(ResultComm.newBuilder().setCode(ResultConstants.CODE_200).setMsg("下发成功").build());
        responseObserver.onCompleted();
    }

    @Override
    public void sendDx(SendDxVO request, StreamObserver<ResultComm> responseObserver) {
        log.info("业务请求—电信平台设备指令发送 request:{}", JSON.toJSONString(request.getAllFields()));
//        executor.execute(() -> {
        DxDataPOJO dxDataPOJO = JSON.parseObject(request.getSendDxVO(), DxDataPOJO.class);
        executor.execute(() -> {
            dataProcessService.addOrder(dxDataPOJO);
//            nbPlantService.ToDxCmd(dxDataPOJO.getIdentity(), dxDataPOJO.getWakeup()!=null?Integer.valueOf(dxDataPOJO.getWakeup()):null,
//                    dxDataPOJO.getCompensation(), dxDataPOJO.getOpen()!=null?new BigDecimal(dxDataPOJO.getOpen()):null);
//        });
        });
        responseObserver.onNext(ResultComm.newBuilder().setCode(ResultConstants.CODE_200).setMsg("下发成功").build());
        responseObserver.onCompleted();
    }

//    public static void main(String[] args) {
//        String name="getService$original$9nT7TpYT";
//        String[] s = name.split("\\$");
//        String s1 = s[0];
//        System.out.println(s1);
//    }

    @Override
    public void universalCall(UniversalVO request, StreamObserver<ResultComm> responseObserver) {
        log.debug("业务请求—通用方法调用 请求数据:{}", JSON.toJSONString(request.getAllFields()));
//        executor.execute(() -> {
        String name = request.getName();
//        String
        String[] s = name.split("\\$");
        name = s[0];
        log.info("业务请求—通用方法调用 请求方法:{}", name);
        Class<DataProcessService> dataProcessServiceClass = DataProcessService.class;
        Object invoke = null;
        for (Method method : dataProcessServiceClass.getMethods()) {
            if (method.getName().equalsIgnoreCase(name)) {
                try {
                    invoke = method.invoke(SpringContextUtil.getBean(dataProcessServiceClass), request.getJson());
                } catch (Exception e) {
                    log.error("调用 方法={} 参数={} 失败: {}", method.getName(), request.getJson(), e);
                }
            }
        }
//        });
//        responseObserver.onNext(ResultComm.newBuilder().setCode(ResultConstants.CODE_200).setMsg("下发成功").setData(ByteString.copyFrom(Objects.requireNonNull(JSON.toJSONBytes(invoke)))).build());
        responseObserver.onNext((ResultComm) invoke);
        responseObserver.onCompleted();
    }
}
